import { UploadOutlined , DownloadOutlined} from '@ant-design/icons';
import useScript from "../../lifecycle/useScript";
import jQuery from 'jquery';
import { ReactSortable } from "react-sortablejs";
import myMessage from "../../utils/message"
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import clsx from 'clsx';
import { Checkbox, Modal, Upload, Button, Tooltip, message, Spin} from "antd";
import { useFormField } from "../../context/form-context";
import { useForm } from "../../context/metadata-context";
import cloneDeep from "lodash/cloneDeep";
import _extend from "lodash/extend";
import uniqBy from "lodash/uniqBy"//去重
import moment from "moment";
import "./index.css";
import { useSelections, useUpdate } from "ahooks";
import request from "../../utils/request";
import { openWin, isIE, buildUrl, formatNumber } from "../../utils";
import ntkoBrowser from "../../../../ntko/ntkobackground.min.js"
import { useInject } from '../../context/inject-context';
import { setFile_sort, checkInFile, updateFile, fileDownload, setDelete_attachments, setValue, deleteFile } from './fileUtilis'; 
import eventBus, { useSubscribe } from '../../eventBus';
import FileItem from './FileItem';

export default function UploadButton ({
  groupId,
  cell,
  fileTypeKey,
  fileInfo,
  multiple,
  tplData,
  urlPrefix,
  csrfToken,
  isTypeFile,
  params
}) {
  let status = useScript("/frontend/build/plupload/plupload.full.min.js");
  
  jQuery.ajaxPrefilter(function (options, originalOptions, xhr) {
    if (
      urlPrefix //window 存在 urlPrefix 属性
      && options.isUrlPrefix !== false //isUrlPrefix = false时， 不需要自动拼接urlPrefix前缀
      && options.url.indexOf('http') !== 0 //请求url不是http开头
      && options.url.indexOf('https') !== 0 //请求url不是https开头
      && options.url.indexOf(window.urlPrefix) !== 0//请求url未拼接 urlPrefix
    ) {
      options.url = urlPrefix + options.url;
    }

    xhr.setRequestHeader('X-CSRF-Token', csrfToken);
  });

  
  if (status === "ready") {
    return <Plupload
            multiple={multiple}
            tplData={tplData}
            groupId={groupId}
            cell={cell}
            fileTypeKey={fileTypeKey}
            fileInfo={fileInfo}
            urlPrefix={urlPrefix}
            csrfToken={csrfToken}
            isTypeFile={isTypeFile}
            params={params}
          ></Plupload> 
  }
  return null;
}

function Plupload({
  groupId,
  tplData,
  cell,
  fileTypeKey,
  fileInfo,
  multiple,
  urlPrefix,
  isTypeFile,
  params,
  csrfToken
}){
  let buttonId = groupId + '-' + cell.code + '-' + fileTypeKey;
  let extensions = tplData?.uploadMimeTypes || "*";//"doc,docx,xls,xlsm,xlsx,ppt,pptx,pdf,xml,jpg,jpeg,png,gif,wmv,asf,flv,tmp,mpp,vsd,txt,rar,zip,bmp,cad,rpt,dwg,avi,mov,mp3,mp4,mpg";
  useLayoutEffect(function(){
    var fileKeyName = Math.random().toString(36).substr(2);
    let max_file_size = 0;//文档上传支持的最大大小 默认为0 也就是不限制
    if(tplData.uploaMaxFileSize){//存在后端配置的最大大小，单位为b，就以后端的为准，后端给0也相当于不限制
      max_file_size = tplData.uploaMaxFileSize;//给上传组件的最大大小限制
    }
    var uploader = new window.plupload.Uploader({
      runtimes: 'html5',//,html4,silverlight,
      browse_button: buttonId, // you can pass in id..
      multi_selection: multiple,//单选多选控制
      url: urlPrefix + '/attachment/ajax-upload1',
      chunk_size: tplData.uploadSplitSize ? tplData.uploadSplitSize/1024 + 'kb' : '1024kb',//分片大小
      filters: {
          max_file_size: max_file_size,//支持的文件最大大小
          mime_types: [
              {
                  extensions: extensions
              }
          ]
      },
      multipart_params: {
          "proc_id":"",
          "node_id":"",
          "chunk":"",
          "chunks":"",
          "isChunked":"",
          "fileSize":"",
          "docName":"",
          "fileKeyName": fileKeyName
      },//上传时的附加参数
      http_method: "POST",
      init: {
          BeforeUpload: function (uploader, file) {
              var multipart_params = {
                fileKeyName: Math.random().toString(36).substr(2),
                fieldCode: cell.code,
                name: file.name,
                fileKeyName: Math.random().toString(36).substr(2),
                fieldCode: cell.code,
                fileSize: file.size,
                docName: encodeURI(file.name),
                business_id: params.business_id,
                package_id: params.package_id || '',
                proc_id: params.proc_id || "",
                node_id: params.node_id || "",
                isChunked: true,//antd没有分片功能
                attachmentTypeGuid: fileTypeKey,
                multiple: multiple,//是否多选
              }
              
              if(file.docUploadRealName){
                multipart_params.docUploadRealName = encodeURI(file.docUploadRealName);
              }
              //上传前给上传接口增加额外的参数
              uploader.setOption({
                  multipart_params: multipart_params,
                  headers: {
                      'X-CSRF-Token': csrfToken
                  },
                  params: multipart_params
              });
          },
          FileFiltered: function (up, file) {
            //校验附件是否可上传
            let verifyResult = verify({
              fileName: file.name,
              fileSize: file.size,
              params: params,
              urlPrefix: urlPrefix
            });
            if(!verifyResult){   
                up.removeFile(file)
                up.stop();
                up.refresh();
                file.isBigFile = true;//校验不通过打上标记
                return false;
            }
          },
          PostInit: function () {

          },
          UploadFile:function(up, file) {
            
          },
          FilesAdded: function (up, files) {//添加附件
            window.plupload.each(files, function (file, index) {
              if(file.isBigFile === true){//在 FileFiltered 内校验不通过的文件
                //不做添加
              }else{
                eventBus.publish("FileUpload.uploadChange" + cell.code + ".update", {
                  file: file,
                  typeKey: fileTypeKey,
                  status: "uploading"
                });
              }
            });
            up.start();//开始上传
          },
          UploadComplete:function (up, file) {
            
          },
          UploadProgress: function (up, file) {
            let fileId = file.id;

            //更当前附件增加上传中标记
            if(!window.__isFileUploading__){
              window.__isFileUploading__ = {};
            }
            if(window.__isFileUploading__[fileId] === undefined){
              window.__isFileUploading__[fileId] = true;//增加上传中标记
            }

            eventBus.publish("FileUpload.uploadChange" + cell.code + ".update", {
              file: file,
              typeKey: fileTypeKey,
              status: "uploading"
            });
          },
          //上传成功
          FileUploaded: function (up, upfile, result) {
            delete window.__isFileUploading__[upfile.id];//删除上传中标记
            
            var rstData = {};
            try {
                rstData = JSON.parse(result.response);//如果是正常返回值，则进行parse
            }catch(e){
                
            }
            
            eventBus.publish("FileUpload.uploadChange" + cell.code + ".update", {
              file: upfile,
              typeKey: fileTypeKey,
              result: rstData,
              status: "done"
            });
            up.refresh();
          },
          //当发生错误时触发监听函数参数：(uploader,errObject)
          Error: function (up, err) {
            
            if(err.code == -601){
              // 获取后缀名
              var index1 = err.file.name.lastIndexOf(".");
              var index2 = err.file.name.length;
              var suffix = err.file.name.substring(index1+1, index2);//后缀名
              myMessage.info({
                content: "文件格式不支持，仅支持上传" + extensions + "类型的文档"
              });
            }else if(err.code === -600){              
              let tipMsg = "文件过大，请调整后上传";
              //如果后端配置的最大上限
              if(tplData.uploaMaxFileSize){
                let uploaMaxFileSize = parseInt(tplData.uploaMaxFileSize/1024/1024);//后端给的单位为b，要/两次1024转为MB
                tipMsg = "文件大小超过限制，上限为" + uploaMaxFileSize + "MB";
              }
              //如果选择的文件大小为0
              if(err.file.size == 0){
                tipMsg = "不支持上传文件大小为0kb的文件";
              }
              myMessage.info({
                content: tipMsg
              });
            }else{
              myMessage.info({
                content: "附件上传出错，请重新上传！"
              });
            }
            if(window?.__isFileUploading__?.[err.file.id]){
              delete window.__isFileUploading__[err.file.id];//删除上传中标记
              eventBus.publish("FileUpload.uploadChange" + cell.code + ".update", {
                file: err.file,
                typeKey: fileTypeKey,
                result: err,
                status: "error"
              });
            }
          }
      }
    });

    uploader.init();
    return function(){
      console.log('销毁');
    }
  },[])

  return <span
            id={buttonId}
            className="inline-block leading-6 cursor-pointer"
          >
              <span
                className="inline-block w-6 h-6 mr-2 leading-5 text-center align-top border border-solid rounded-sm shade op-upload-check op-upload border-d9d9d9 text-gray-b1"
                
                data-filecode={cell.code}
                attachment-type={fileTypeKey}
              >
                {React.createElement(UploadOutlined)}
              </span>
                {fileInfo.name || "上传附件"}
          </span>
}


//上传前校验文件是否合法
var verify = function({
  fileName,
  fileSize,
  params
}){
  try{
    
      var rsp = jQuery.ajax(
        {
          url: "/attachment/verify-file?fileName="+escape(fileName)+"&fileSize="+fileSize+"&package_id=" + params.package_id || '',
          async: false,
          type: 'get'
        }
      ).responseJSON;
      if(rsp.code === 1) {
        return true;
      }
      
      var erro = "";
      if(typeof rsp.message !== "undefined") {
        erro = rsp.message;
      }
      if(erro.indexOf("||")>-1){
          var errSplit = erro.split("||");
          myMessage.info({
            title:errSplit[0],
            content: errSplit[1]
          });
      }else{
        myMessage.info({
          content: erro || "文件格式或大小不合法！"
        });
      }
      return false;
  }
  catch(e){
      return false;
  }

};
/*
function verifyFile(file){
  return new Promise((resolve, reject)=>{
    request({
      url: "/attachment/verify-file?fileName="+escape(file.name)+"&fileSize="+ file.size + "&package_id=" + params.package_id || '',
      method: "get",
      noTip: true//请求错误时，axios不展示公共错误
    }).then(function(rsp){
      if(rsp.code === 1) {//校验成功
        resolve(file);//校验成功
        return true;
      }
      reject();//校验失败
    
      //失败提示
      let erro = rsp?.message || "";
      if(erro === ""){
        erro = "文件格式或大小不合法！";
      }
      failTip(erro);
    },function(errorRes){
      reject();//校验失败
      myMessage.info({
        content: "文件格式或大小不合法！"
      });
    })
  });
}
 */

/*

<Upload 
  key={cell.code + '-' + fileTypeKey}
  {...uploadConfig}
  data={ 
    (file)=>{
      //上传前设置额外参数
      let data = {
        name: file.name,
        chunk: 0,//分片索引 先写死0，因为没分片功能
        chunks: 1,//分片数量 先写死1，因为没分片功能，默认是1个分片
        fileKeyName: Math.random().toString(36).substr(2),
        fieldCode: cell.code,
        fileSize: file.size,
        docName: encodeURI(file.name),
        business_id: params.business_id,
        package_id: params.package_id || '',
        proc_id: params.proc_id || "",
        node_id: params.node_id || "",
        isChunked: false,//antd没有分片功能
        attachmentTypeGuid: fileTypeKey,
        multiple: cell.props.is_support_multiple_file,//是否多选
      };
      return data;
    }
  }
  onChange={({file, fileList})=>{
    _uploadChange({
      file: file,
      fileList: fileList,
      typeKey: fileTypeKey
    });
  }}
  showUploadList={false}
  name={'file'}
  action={urlPrefix + '/attachment/ajax-upload1'}
  headers = {
    {
      'x-csrf-token': csrfToken
    }
  }
>
  <span
    className="inline-block w-6 h-6 mr-2 text-center border border-solid rounded-sm cursor-pointer shade op-upload-check op-upload border-d9d9d9 text-gray-b1"
    id={cell.code + '-' + fileTypeKey}
    key={cell.code + '-' + fileTypeKey}
    data-filecode={cell.code}
    attachment-type={fileTypeKey}
  >
    {React.createElement(UploadOutlined)}
  </span>
  {fileInfo.name || "上传附件"}
</Upload>
 */